import Store from "@/store";
import atlas from "@/atlas";

// 对接口数据进行处理
const topicItemStyleData = (item, type) => {
    if (!item.style) return {};
    let { top, left, width, height } = item.style;
    width = width + 8;
    height = height + 8;
    if (item.contentType === "video") {
        // 宽高占比
        // +1补足四舍五入差值
        // 708 / 846 = 0.836
        width = parseInt(width * 0.836) + 1;
        // 398 / 490 = 0.812
        height = parseInt(height * 0.812) + 1;
    }
    let styleInfo = {
        // width: `${type == 1 ? width + 2 : width}px`,
        // height: `${type == 1 ? height + 2 : height}px`,
        width: width,
        height: height,
    };
    if (type == 1) {
        styleInfo["top"] = `${top}px`;
        styleInfo["left"] = `${left}px`;
    }
    return styleInfo;
};

const cornerImgTypeArr = [
    "upperLeftCornerImage",
    "downLeftCornerImage",
    "upperRightCornerImage",
    "downRightCornerImage",
    "centerCornerImage",
];

// 整理21号组件（频道小窗播放及右侧列表数据）
function handleData21(data, rowIndex, isHaveTopStatus) {
    let items = data.items;
    let topicHeight = 0;
    let defaultPlayInfo = Store.storeData.playerInfoData;
    let animationIntervalData = null;
    let horizontalscrollData = null;
    // 是否带有视频播放器组件
    let videoSmallStatus = false;
    let videoSmallContentIndex = 0;
    let contentSetsList = [];
    let contentNamesList = [];
    let contents = "";
    // 是否最顶部的topic
    let topicTopStatus = false;
    if (rowIndex === 0) {
        Store.setData("topicScrollTop", 0);
    }
    let topicScrollTopValue = Store.storeData.topicScrollTop;
    let topicScrollBottomValue = Store.storeData.topicScrollTop;
    // 是否有title
    const isHaveTitle = ["21"].includes(data.layoutType) && data.title;
    for (let index = 0; index < items.length; index++) {
        const element = items[index];
        contents += (element.itemId || "") + ",";
        items[index]["rowIndex"] = index;
        items[index]["topicRowIndex"] = rowIndex;
        if (element.style.left && element.style.width) {
            items[index]["isRightStatus"] =
                element.style.left + element.style.width >= 1650;
        }
        if (!isHaveTopStatus) {
            items[index]["isTopStatus"] = true;
            topicTopStatus = true;
        }
        if (__IS_DEV__ && element.contentType === "video") {
            items[index]["autoPlay"] = "1";
            items[index]["contents"] = element.contents.concat([
                {
                    ...element.contents[0],
                    contentId: "1948949145519651234",
                    contentImage:
                        "http://images.center.bcs.ottcn.com:8080/images/ysten/picture/ndms/cmjs/2023/08/04/39b1499e573943aa9e4a815d18bd751e.png",
                },
            ]);
        }
        // const isTopStatus = element.style.top === 0 && rowIndex === 0
        if (element.contentType === "video" && element.style) {
            videoSmallStatus = true;
            Store.setData("videoSmallIndex", rowIndex);
            videoSmallContentIndex = index;
            // 490 / 846 = 0.58
            element.style.height = parseInt(element.style.width * 0.58);
            const times = element.style.width / 846;
            element.style.focusTop = parseInt(42 * times);
            element.style.focusLeft = parseInt(56 * times);
            element.style.positionTop = parseInt(52 * times);
            element.style.positionLeft = parseInt(66 * times);
            element.style.focusWidth = parseInt(728 * times);
            element.style.focusHeight = parseInt(418 * times);
        }
        if (element.style.left === 0) {
            topicScrollBottomValue =
                topicScrollBottomValue + element.style.height;
        }
        items[index]["styleInfo1"] = topicItemStyleData(element, 1);
        items[index]["styleInfo2"] = topicItemStyleData(element, 2);
        // if (__IS_DEV__) {
        //     items[index]["backgroundImage"] =
        //         "http://images.center.bcs.ottcn.com:8080/images/ysten/picture/ndms/cmjs/2023/07/28/22ae6eebb33349c1af489279bb989203.png";
        // }
        if (!element.style) break;
        let { top, height } = element.style;
        let newHeight = top + height;
        if (top && newHeight > topicHeight) {
            topicHeight = newHeight;
        } else if (height > topicHeight) {
            topicHeight = height;
        }
        let contentSets = "";
        let contentNames = "";
        if (element.contents?.length) {
            for (let index2 = 0; index2 < element.contents.length; index2++) {
                let contentEle = element.contents[index2];
                contentSets +=
                    (contentEle.contentUrl || contentEle.actionUrl || "") + ",";
                let name =
                    contentEle.contentName ||
                    contentEle.liveChannelData?.liveChannelName ||
                    "";
                contentNames += name + ",";
                contentEle["rowIndex"] = index2;
                contentEle["itemId"] = element.itemId;
                contentEle["contentType"] = element.contentType;
                // contentEle["upperLeftCornerImage"] = index ?"http://192.168.48.89:8081/cj/images/fufei_2.png": "http://192.168.48.89:8081/cj/images/fufei_1.png"
                // horizontalscroll
                if (element.contentType === "horizontalscroll") {
                    contentEle["type"] = "120";
                }
                // if (__IS_DEV__ && rowIndex == 3) {
                //     contentEle["actionUrl"] = "kidsplayer_web_watchHistory";
                // }
                // 角标位置（1|2|3|4|5）1左上；2左下；3右上 4右下；5：中间
                let cornerImgList = [];
                for (
                    let cornerIndex = 0;
                    cornerIndex < cornerImgTypeArr.length;
                    cornerIndex++
                ) {
                    const cornerItem = cornerImgTypeArr[cornerIndex];
                    if (contentEle[cornerItem]) {
                        let typeValue = cornerIndex + 1;
                        cornerImgList.push({
                            type: typeValue,
                            img: contentEle[cornerItem],
                            top:
                                typeValue == 5
                                    ? parseInt((element.style.height - 120) / 2)
                                    : 0,
                        });
                    }
                }
                contentEle["cornerImgList"] = cornerImgList;
                if (element.contentType === "video") {
                    // contentEle["isTopStatus"] = isTopStatus
                    if (__IS_DEV__) {
                        contentEle.contentUrl =
                            "http://221.131.123.204:4389/cj/shaoer-test.mp4";
                    }
                    if (!defaultPlayInfo) {
                        defaultPlayInfo = contentEle;
                        Store.setData("playerInfoData", contentEle);
                    }
                }
            }
            contentSetsList.push(contentSets.slice(0, -1));
            contentNamesList.push(contentNames.slice(0, -1));
        }
        // animation
        if (
            element.contentType === "animation" &&
            Number(element.timeInterval) &&
            element.contents.length
        ) {
            if (!animationIntervalData) animationIntervalData = {};
            animationIntervalData[`animation_${rowIndex}_${index}`] = {
                timeInterval: Number(element.timeInterval),
                currentSlideNum: 0,
                timeCount: 0,
                slideNum: element.contents.length,
                isLastOver: false,
            };
        }
        // horizontalscroll
        if (
            element.contentType === "horizontalscroll" &&
            element.contents.length
        ) {
            if (!horizontalscrollData) horizontalscrollData = {};
            horizontalscrollData[`horizontalscroll_${rowIndex}`] = {
                contents: element.contents,
            };
        }
    }
    if (isHaveTitle) {
        topicScrollBottomValue += 90;
    }
    Store.setData("topicScrollTop", topicScrollBottomValue);
    const result = {
        ...data,
        desktopId: data.desktopId,
        flowId: data.flowId,
        topicId: data.topicId,
        itemId: items[0].itemId,
        items: items,
        topicHeight: topicHeight,
        rowIndex: rowIndex,
        animationIntervalData: animationIntervalData,
        horizontalscrollData: horizontalscrollData,
        type: String(rowIndex),
        contents: contents,
        content_sets: contentSetsList.join("|"),
        content_names: contentNamesList.join("|"),
        titleColor: data.titleColor || "#ffffff",
        videoSmallStatus: videoSmallStatus,
        videoSmallContentIndex: videoSmallContentIndex,
        isTopStatus: topicTopStatus,
        topicScrollTop: topicScrollTopValue,
        topicScrollBottom: topicScrollBottomValue,
        // type: "120"
    };
    return result;
}

// 推荐位跳转
function recommendJump(data) {
    console.log("navigateRouteTo0", data, data.actionType);
    switch (data.actionType) {
        case "app": // app
            var jumpUrl = _formatApk(data.appData);
            var _url1 = {
                p1: "Android",
                p2: `${jumpUrl}`,
                p3: "",
            };
            atlas.goCommonJump(_url1);
            break;
        case "ps": // 节目集
            console.log("navigateRouteTo1", data.actionUrl, new Date());
            Store.emit("navigateRouteTo", {
                name: "detail",
                data: { psId: data.actionUrl },
            });
            break;
        case "topic": // 链接
            atlas.openGefo(data.actionUrl);
            break;
        case "custom": // 链接
            // if (data.actionUrl.indexOf("com.ysten.wk")) {
            //     recommendJumpWk(data.actionUrl)
            // } else {
                
            // }
            var _url = {
                p1: "OpenUrl",
                p2: data.actionUrl,
                p3: "",
            };
            atlas.goCommonJump(_url);
            break;
        default:
            atlas.openGefo(data.actionUrl);
            break;
    }
}

// 推荐位跳转快应用
function recommendJumpWk(url) {
    var params = JSON.stringify({
        pageType: "secondaryPage", // 非必传, 跳转二级页必传
    }) // params为enteryPage配置参数
    atlas.newApp(url,params)
}

function _isObject(obj) {
    return Object.prototype.toString.call(obj) === "[object Object]";
}

// 转化成访问apk使用的格式
function _formatApk(params) {
    var url = "";
    console.log(
        "log._formatApk:",
        params,
        Object.prototype.toString.call(params)
    );
    if (_isObject(params)) {
        var pkgName =
            params.packageName ||
            params?.component?.pkg ||
            params?.package ||
            ""; // app包名
        var clsName = params.className || params?.component?.cls || ""; // app类名
        var downloadUrl = params.apkUrl || params?.downloadUrl || ""; // 下载地址
        var appId = params.appId || ""; // appid
        var appForceUpdate =
            params.forceUpdate ||
            params?.appForceUpdate ||
            (downloadUrl ? 0 : 1); // 是否强制更新
        var appVersion = params.version || params?.appVersion || ""; // app版本信息
        var appAction = params.action || params?.appAction || ""; // 应用跳转的action
        var uri = params.outerApkUrl || params?.uri || ""; // 淘宝等使用url打开的app调用地址
        var appName = params.appName || ""; // app名称

        var extras = params?.extra || params?.extras || params?.params || ""; // 扩展信息
        var extArr = []; //记录扩展字段的数组
        var extObj = {}; //临时对象
        var extResult = "[]"; //数组转换成字符串
        if (extras) {
            if (Array.isArray(extras)) {
                let newExtras = {};
                for (const iterator of extras) {
                    newExtras = {
                        ...newExtras,
                        ...iterator,
                    };
                }
                extras = newExtras;
            }
            for (var name in extras) {
                extObj = {};
                extObj["key"] = name + "";
                extObj["value"] = (extras[name] || "") + "";
                extArr.push(JSON.stringify(extObj));
                extObj = null;
            }
            extResult = "[" + extArr.join(",") + "]";
        }
        console.log("log._formatApk:extResult", extResult);
        if (pkgName) {
            url =
                '{"pkg":"' +
                pkgName +
                '", "cls":"' +
                clsName +
                '", "downloadUrl":"' +
                downloadUrl +
                '", "appId":"' +
                appId +
                '", "appForceUpdate":"' +
                appForceUpdate +
                '", "appVersion":"' +
                appVersion +
                '", "appAction":"' +
                appAction +
                '", "uri":"' +
                uri +
                '", "appName":"' +
                appName +
                '","params":' +
                extResult +
                "}";
        }
    }
    console.log("log._formatApk:", url);
    return url;
}

// 恢复焦点
function restRequestFocus(saveFocusInfo, _this) {
    let focusInfo = saveFocusInfo || Store.storeData.saveFocusInfo;
    console.log("hideTipsDialogAction", _this, focusInfo);
    if (!focusInfo) {
        return;
    }
    if (focusInfo.ref) {
        const fatherRef = focusInfo.fatherRef
            ? _this.$refs[focusInfo.fatherRef]
            : _this.$refs[focusInfo.ref];
        const refs = focusInfo.fatherRef
            ? fatherRef.$refs[focusInfo.ref]
            : focusInfo.fatherRef;
        console.log(
            "hideTipsDialogAction:refs",
            focusInfo.fatherRef,
            focusInfo.ref,
            fatherRef,
            refs
        );
        if (refs) {
            Store.storeData.saveFocusInfo = null;
            if (typeof focusInfo.index === "number") {
                // 使用tvList上焦
                refs.requestChildFocus(focusInfo.index);
            } else {
                // 直接上焦
                if (typeof focusInfo.refIndex === "number") {
                    atlas.requestFocus(refs[focusInfo.refIndex]);
                } else {
                    atlas.requestFocus(refs);
                }
            }
        }
    }
}

export default {
    handleData21, // 整理21号组件信息
    recommendJump: recommendJump,
    recommendJumpWk: recommendJumpWk,
    restRequestFocus: restRequestFocus,
};
